package com.yunhe.job.runner;

import com.yunhe.job.domain.ElasticJobConfigBean;
import com.yunhe.job.service.ElasticJobService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 定时任务配置
 * @author liuronglei
 */
@Component
public class ElasticJobRunner implements CommandLineRunner {

	private static final Map<String, String> JOB_CONFIG_MAP = new ConcurrentHashMap<>();

	@Resource
	private ElasticJobService elasticJobService;

	/**
	 * 根据jobName获取配置
	 * @param jobName
	 * @return
	 */
	public static String getJobConfig(String jobName) {
		return JOB_CONFIG_MAP.get(jobName);
	}

	/**
	 * 更改jobConfig
	 * @param jobName
	 * @param jobConfig
	 */
	public static void setJobConfig(String jobName, String jobConfig) {
		JOB_CONFIG_MAP.put(jobName, jobConfig);
	}

	@Override
	public void run(String... args) throws Exception {
		List<ElasticJobConfigBean> elasticJobConfigList = (List<ElasticJobConfigBean>)elasticJobService.getElasticJobConfigList(null);
		if (elasticJobConfigList == null || elasticJobConfigList.size() == 0) {
			return;
		}
		elasticJobConfigList.forEach(elasticJobConfig -> {
			elasticJobService. registryJob(elasticJobConfig);
			JOB_CONFIG_MAP.put(elasticJobConfig.getJobName(), elasticJobConfig.getJobConfig());
		});
	}
}
